/*
 * Copyright 2012 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fujitsu.nanjing.tieba.base.BaseService;
import com.fujitsu.nanjing.tieba.constrant.CommonParamter;
import com.fujitsu.nanjing.tieba.ibator.CoreUser;
import com.fujitsu.nanjing.tieba.ibator.CoreUserCriteria;
import com.fujitsu.nanjing.tieba.model.User;

/**
 * UserService.java
 * 
 * @author Qixiaobo-win8
 */
@Transactional
@Service
public class UserService extends BaseService<CoreUser, CoreUserCriteria> {
	@Resource
	private User user;
	@Override
	public CoreUser findById(String id) {
		return user.selectByPrimaryKey(id);
	}

	@Override
	public CoreUser insert(CoreUser t) {
		t.setGroupid(CommonParamter.新手上路);
		t.setLogincount((byte) 1);
		t.setLastvisited(new Date());
		t.setLoginexpire(DateUtils.addMinutes(new Date(), 30));
		user.insert(t);
		return t;

	}
	@Override
	public void update(CoreUser t) {
		user.updateByPrimaryKeySelective(t);
	}

	@Override
	public void delete(CoreUser t) {
		user.deleteByPrimaryKey(t.getUserid());

	}

	public int findByEmail(String Email) {
		CoreUserCriteria example = new CoreUserCriteria();
		example.createCriteria().andEmailEqualTo(Email);
		return user.countByExample(example);
	}
	/**
	 * 获取用户昵称，如果为空，则返回用户id
	 ***/
	public String getUserName(String userId) {
		CoreUser coreUser = user.selectByPrimaryKey(userId);
		return coreUser.getNickname() == null ? coreUser.getUserid() : coreUser
				.getNickname();
	}

	public CoreUser findByIdAndPwd(String userId, String pwd) {
		CoreUserCriteria example = new CoreUserCriteria();
		example.createCriteria().andPwdEqualTo(pwd).andUseridEqualTo(userId);
		List<CoreUser> userList = user.selectByExample(example);
		if (userList != null && userList.size() != 0) {
			return userList.get(0);
		}
		return null;

	}
	/** 由于登陆需要更改相关数据 **/
	public void updateWhileLogin(CoreUser coreUser, String CookieValue) {
		if (!CookieValue.equals("0")) {
			coreUser.setLoginexpire(DateUtils.addMinutes(new Date(),
					Integer.parseInt(CookieValue) / 60));

		}
		// TODO Auto-generated method stub

	}
}
